package com.group01.community.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author guoyuan
 * @date @since 2025-05-01
 */
public class JwtUtil {

    public static final String JWT_KEY_USERNAME = "username";
    public static final int EXPIRE_MINUTES = 120;

    /**
     * 私钥加密Token
     * @param username 需要解密的数据
     * @param privateKey 私钥
     * @param expireMinutes 过期时间
     * @return 加密后的token
     */
    public static String generateToken(String username, PrivateKey privateKey, int expireMinutes) {
        return Jwts.builder().claim(JWT_KEY_USERNAME, username)
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    /**
     * 解析用户信息
     * @param token 传入token
     * @param publicKey 公钥
     * @return 用户信息
     */
    public static String getJwtKeyUsername(String token, PublicKey publicKey) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String username = (String) body.get(JWT_KEY_USERNAME);
        return username;
    }
}
